// import store from '@/store'
import axios from 'axios'
// import { getToken } from '@/utils/auth'

const service = axios.create({
  // baseURL: '/api',
  timeout: 8000
})
const getToken = () => window.localStorage.getItem('token')
service.interceptors.request.use(
  config => {
    if (getToken()) {
      // config.headers.Authorization = getToken()
      // const token = window.localStorage.getItem('token')
      config.headers.Authorization = getToken()
    }
    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

service.interceptors.response.use(
  response => {
    var data = response.data
    var { resRoute, resType, addHierarchy } = param2Obj(response.config.url)
    if (resRoute) {
      // eslint-disable-next-line no-eval
      data = eval(
        'data' +
          (resRoute && resRoute.length
            ? '["' + resRoute.split('.').join('"]["') + '"]'
            : '')
      )
    }
    if (addHierarchy) {
      var list = addHierarchy.split('.')
      var s = ''
      var e = ''
      for (var i in list) {
        // eslint-disable-next-line no-unused-expressions
        list[i]
        s += `{"${list[i]}": `
        e += '}'
      }
      try {
        data = JSON.parse(s + JSON.stringify(data) + e)
      } catch (error) {
        console.log(error)
      }
    }
    if (resType === 'updata') {
      try {
        data = {
          data: {
            ...data,
            url: '/api/activiti/file/preview?id=' + data.id
          }
        }
      } catch (error) {
        console.log(error)
      }
    }
    console.log(data)
    return { data: data }
  },
  error => {
    console.log(error)

    const { status } = error.response

    if (status === 401) {
      // to re-login
      // 提示没有权限，重新登录
    }

    // const message = error.message
    // Toast(message, { position: 'bottom' })

    return Promise.reject(error)
  })

function param2Obj (url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

export default service
